# uncompyle6 version 3.2.3
# Python bytecode 3.6 (3379)
# Decompiled from: Python 3.6.8 |Anaconda custom (64-bit)| (default, Feb 21 2019, 18:30:04) [MSC v.1916 64 bit (AMD64)]
# Embedded file name: helpers\licensing\usage.py
__author__ = "Attila Gerendi (Sanyi)"
import json, os.path, logging
from sqlalchemy import select as sql_select
from sqlalchemy import func as sql_func
from sqlalchemy import distinct as sql_distinct
from helpers.setup_types import is_setup_type_on_premise_master
from db import Connection
from db.tables.targets import TargetRow, TargetTypes
from settings_provider import settings

_logger = logging.getLogger("helpers.target.license_usage")


def update_license_usage():
    if not is_setup_type_on_premise_master():
        return
    try:
        q = (
            sql_select((sql_func.count(sql_distinct(TargetRow.cah)),))
            .where(TargetRow.deleted_at.is_(None))
            .where(TargetRow.type == TargetTypes.DEFAULT)
        )
        with Connection("master") as (db):
            c = db.execute(q).scalar()
            output = json.dumps(dict(unique_std_target_count=c))
            license_usage_file_path = os.path.join(
                settings.get("storage.license", ""), "license_usage.json"
            )
            open(license_usage_file_path, "wt").write(output)
    except Exception as e:
        _logger.exception("update_license_usage failed with %s", e)
